import React, { useState, useCallback, useRef } from 'react';
import {
  KeyboardAvoidingView, StyleSheet, Keyboard, ActivityIndicator, View
} from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';

import { Tip } from 'beeshell';

import {
  Block, Text, Input, Button
} from '../components';
import { colors, sizes } from '../constants/theme';
import Http from '../service/http';
import { setToken, getInfo } from '../service/token';
import NavigationUtil from '../navigation/NavigationUtil';

export default function Login({ navigation }) {
  const [userId, setUserId] = useState('');
  const [password, setPassword] = useState('');
  const [errors, setErrors] = useState([]);
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState(null);
  const errorTip = useRef(null);

  const handleLogin = useCallback(async () => {
    const errorArray = [];
    Keyboard.dismiss();
    setLoading(true);
    const { data, status } = await Http.auth({ userId, password });
    if (status !== 200 && status !== 400) {
      Tip.show('网络请求错误');
      setLoading(false);
    } else {
      const { status: s, data: d, message } = data;
      if (s !== '200') {
        errorArray.push('userId', 'password');
        setLoading(false);
        setErrors(errorArray);
        setErrorMsg(message);
        errorTip.current.open();
      } else {
        setLoading(false);
        const { token } = d;
        await setToken(token);
        const { role } = await getInfo();
        if (role === 1) {
          NavigationUtil.navigateWithWSInit(navigation, 'Manager');
        } else if (role === 3) {
          NavigationUtil.navigateWithWSInit(navigation, 'Worker');
        } else {
          setErrorMsg('权限错误');
          errorTip.current.open();
        }
      }
    }
  }, [userId, password, navigation]);

  const hasErrors = useCallback(
    (key) => (errors.includes(key) ? styles.hasErrors : null), [errors]
  );

  return (
    <KeyboardAvoidingView style={styles.login} behavior="padding">
      <Block padding={[0, sizes.base * 2]}>
        <Text h1 bold>
          登录
        </Text>
        <Block middle>
          <Input
            label="工号"
            error={hasErrors('userId')}
            style={[styles.input, hasErrors('userId')]}
            onChangeText={(text) => setUserId(text)}
          />
          <Input
            secure
            label="密码"
            error={hasErrors('password')}
            style={[styles.input, hasErrors('password')]}
            onChangeText={(text) => setPassword(text)}
          />
          <Button
            gradient
            onPress={() => handleLogin()}
          >
            {loading
              ? <ActivityIndicator size="small" color="white" /> : (
                <Text bold white center h3>登录</Text>
              )}
          </Button>
          <Tip
            ref={errorTip}
            duration={2000}
            body={(
              <View>
                <AntDesign
                  name="closecircleo"
                  size={20}
                  style={{ color: colors.white, textAlign: 'center', paddingBottom: 10 }}
                />
                <Text style={{ color: colors.white }}>{errorMsg}</Text>
              </View>
            )}
          />
        </Block>
      </Block>
    </KeyboardAvoidingView>
  );
}


const styles = StyleSheet.create({
  login: {
    flex: 1,
    justifyContent: 'center',
  },
  loginButton: {
    backgroundColor: colors.primary,
  },
  input: {
    borderRadius: 0,
    borderWidth: 0,
    borderBottomColor: colors.gray2,
    borderBottomWidth: StyleSheet.hairlineWidth,
  },
  hasErrors: {
    borderBottomColor: colors.accent,
  },
});
